import { useCallback } from 'react';
import { message } from 'antd';

interface ErrorHandlerOptions {
  showMessage?: boolean;
  defaultMessage?: string;
  onError?: (error: any) => void;
}

export const useErrorHandler = () => {
  const handleError = useCallback((
    error: any, 
    options: ErrorHandlerOptions = {}
  ) => {
    const {
      showMessage = true,
      defaultMessage = '操作失败，请稍后重试',
      onError
    } = options;

    console.error('Error occurred:', error);

    if (showMessage) {
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          defaultMessage;
      message.error(errorMessage);
    }

    if (onError) {
      onError(error);
    }
  }, []);

  const handleAsyncError = useCallback(async <T>(
    asyncFn: () => Promise<T>,
    options: ErrorHandlerOptions = {}
  ): Promise<T | null> => {
    try {
      return await asyncFn();
    } catch (error) {
      handleError(error, options);
      return null;
    }
  }, [handleError]);

  return {
    handleError,
    handleAsyncError
  };
};
